"""
Description:
Author: 月间
Date: 2025-08-16 21:36:21
LastEditTime: 2025-11-09 22:32:22
LastEditors:
"""

from typing import List, Optional

from tortoise import fields
from tortoise.models import Model


class Dept(Model):
    id = fields.IntField(pk=True, description="部门ID")
    parent_id = fields.IntField(description="父级编号", default=0)
    # ancestors 格式: "/1/2/" (不包含自己，使用/分隔)
    ancestors = fields.CharField(max_length=255, description="祖籍列表", default="")
    dept_name = fields.CharField(max_length=50, description="部门名称")
    sort = fields.IntField(description="排序", default=0)
    leader = fields.CharField(max_length=50, description="负责人")
    phone = fields.CharField(max_length=20, description="联系方式")
    email = fields.CharField(max_length=50, description="邮箱")
    status = fields.IntField(description="状态(1开启,0关闭)", default=1)
    remark = fields.TextField(description="备注", null=True)
    address = fields.CharField(max_length=255, description="详细地址", null=True)
    create_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
    update_at = fields.DatetimeField(auto_now=True, description="更新时间")

    class Meta:
        table = "admin_dept"
        # 为 ancestors 创建索引，支持前缀匹配
        indexes = [
            ("ancestors",),
            ("parent_id", "sort"),
        ]

    def get_ancestor_ids(self) -> List[int]:
        """
        获取祖先ID列表（不含自己）
        ancestors="/1/2/" => [1, 2]
        """
        if not self.ancestors:
            return []
        return [int(x) for x in self.ancestors.strip("/").split("/") if x]

    def get_ancestor_ids_with_self(self) -> List[int]:
        """获取祖先ID列表（含自己）"""
        ancestor_ids = self.get_ancestor_ids()
        return ancestor_ids + [self.id]

    def get_level(self) -> int:
        """
        获取部门层级（顶级为1）
        ancestors="" => level=1
        ancestors="/1/" => level=2
        ancestors="/1/2/" => level=3
        """
        if not self.ancestors:
            return 1
        return len(self.get_ancestor_ids()) + 1

    async def get_parent(self) -> Optional["Dept"]:
        """获取父部门"""
        if not self.parent_id or self.parent_id == 0:
            return None
        return await Dept.get_or_none(id=self.parent_id)

    async def get_ancestors(self) -> List["Dept"]:
        """获取所有祖先部门对象"""
        ancestor_ids = self.get_ancestor_ids()
        if not ancestor_ids:
            return []
        # 按照 ancestors 中的顺序返回
        depts = await Dept.filter(id__in=ancestor_ids).all()
        # 排序保持祖先顺序
        dept_dict = {dept.id: dept for dept in depts}
        return [dept_dict[aid] for aid in ancestor_ids if aid in dept_dict]

    async def get_children(self, recursive: bool = False) -> List["Dept"]:
        """
        获取子部门
        recursive=True: 获取所有子孙部门
        recursive=False: 只获取直接子部门
        """
        if recursive:
            # 使用前缀匹配，可以利用索引
            return await Dept.filter(ancestors__startswith=f"/{self.id}/").order_by("sort", "id")
        else:
            return await Dept.filter(parent_id=self.id).order_by("sort", "id")

    def is_ancestor_of(self, dept: "Dept") -> bool:
        """判断是否是某部门的祖先"""
        # 检查目标部门的 ancestors 是否包含自己的ID
        return f"/{self.id}/" in dept.ancestors or dept.ancestors.startswith(f"/{self.id}/")

    def is_descendant_of(self, dept_id: int) -> bool:
        """判断是否是某部门的子孙"""
        ancestor_ids = self.get_ancestor_ids()
        return dept_id in ancestor_ids

    def get_ancestors_path(self) -> str:
        """
        获取完整路径（含自己）
        ancestors="/1/2/" => "/1/2/3/"
        """
        if self.ancestors:
            return f"{self.ancestors}{self.id}/"
        return f"/{self.id}/"
